package com.minke.ch11springbootinterceptor.interceptor;

import com.minke.ch11springbootinterceptor.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 何杨谊
 * @description: TODO
 * @date 2022/4/3 22:19
 */
public class UserIntercpetor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //编写业务拦截器规则
        //从session中获取用户信息
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            //未登录
            response.sendRedirect(request.getContextPath() + "/api/user/open/no-login");
            return false;
        } else {
            //已登录
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
